import { useTestResults } from '@/contexts/TestResultsContext';
import { useNavigation } from 'expo-router';
import React, { useEffect, useRef, useState } from 'react';
import {
    Alert,
    SafeAreaView,
    ScrollView,
    StyleSheet,
    Text, ToastAndroid,
    TouchableOpacity,
    View
} from 'react-native';
import { BroadcastReceiver } from "react-native-broadcast-receiver";
import { Codes, Parity, UsbSerial, UsbSerialManager } from "react-native-usb-serialport-for-android";
import { useAudioPlayer } from 'expo-audio';

interface TestParams {
    freq: number;
    brightness: number;
}

interface TestResult {
    params: TestParams;
    sawFlicker: boolean;
    timestamp: number;
}

const FlickerDevice: React.FC = () => {
        const [isTesting, setIsTesting] = useState(false);
        const [cleanConnection, setCleanConnection] = useState(false);
        const [currentTest, setCurrentTest] = useState(0);
        const [countdown, setCountdown] = useState(10);
        const [testResults, setTestResults] = useState<TestResult[]>([]);
        const [usbSerialport, setUsbSerialport] = useState<UsbSerial | null>(null);
        const [isConnected, setIsConnected] = useState(false);
        const [hasPermission, setHasPermission] = useState(false);
        // 显示间隔状态
        const [isInterval, setIsInterval] = useState(false);
    const [intervalCountdown, setIntervalCountdown] = useState(3);
    const [showCompletionDialog, setShowCompletionDialog] = useState(false);
        
        // 使用 useRef 存储定时器引用，避免不必要的重新渲染
        const timerRef = useRef<any>(null);
        const intervalTimerRef = useRef<any>(null);
        const healthCheckIntervalRef = useRef<any>(null);
        const {addTestResult} = useTestResults();
        const navigation = useNavigation();
        
        // 使用 useAudioPlayer hook 创建音频播放器
        const audioSource = require('../../assets/mp3/notice.mp3');
        const player = useAudioPlayer(audioSource);

    const playNotificationSound = () => {
        try {
            // 重置到开头并播放
            player.seekTo(0);
            player.play();
        } catch (error) {
            console.error('Error playing sound:', error);
        }
    };

        // 统一的定时器清理函数
        const clearAllTimers = () => {
            if (timerRef.current) {
                clearInterval(timerRef.current);
                timerRef.current = null;
            }
            if (intervalTimerRef.current) {
                clearInterval(intervalTimerRef.current);
                intervalTimerRef.current = null;
            }
            if (healthCheckIntervalRef.current) {
                clearInterval(healthCheckIntervalRef.current);
                healthCheckIntervalRef.current = null;
            }
        };

        // 测试序列 (固定亮度50%，6种随机频率)
        const baseTestSequence: TestParams[] = [
            {freq: 15, brightness: 50},
            {freq: 18, brightness: 50},
            {freq: 22, brightness: 50},
            {freq: 45, brightness: 50},
            {freq: 48, brightness: 50},
            {freq: 50, brightness: 50}
        ];

        // Fisher-Yates洗牌算法实现随机排序
        const shuffleArray = (array: TestParams[]) => {
            const newArray = [...array];
            for (let i = newArray.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
            }
            return newArray;
        };

        const [testSequence, setTestSequence] = useState<TestParams[]>([]);

        // 请求USB权限
        const requestUSBPermission = async (deviceId: number): Promise<boolean> => {
            try {
                const granted = await UsbSerialManager.tryRequestPermission(deviceId);
                setHasPermission(granted);
                return granted;
            } catch (error) {
                setHasPermission(false);
                return false;
            }
        };

        // 检查并连接USB设备
        const connectUSBDevice = async () => {
            try {
                console.log('开始连接USB设备...');
                
                const devices = await UsbSerialManager.list();
                console.log('可用USB设备:', devices);

                if (devices.length === 0) {
                    console.log('未找到USB设备');
                    Alert.alert('设备未找到', '请检查频闪设备是否已连接');
                    return null;
                }

                const device = devices[0];
                console.log('选择设备:', device);

                const permissionGranted = await requestUSBPermission(device.deviceId);
                if (!permissionGranted) {
                    console.log('USB权限获取失败');
                    return null;
                }
                console.log('USB权限获取成功');

                // 尝试连接设备
                console.log('尝试打开串口...');
                const serialPort = await UsbSerialManager.open(device.deviceId, {
                    baudRate: 115200,
                    parity: Parity.None,
                    dataBits: 8,
                    stopBits: 1
                });

                // 验证串口是否真正打开
                if (!serialPort) {
                    console.log('串口打开失败');
                    return null;
                }
                console.log('串口打开成功');

                // 设置数据接收监听
                const subscription = serialPort.onReceived((event: any) => {
                    console.log('收到数据:', event.deviceId, event.data);
                });

                // 等待连接稳定
                console.log('等待连接稳定...');
                await new Promise(resolve => setTimeout(resolve, 1000));

                // 尝试发送一个测试命令来验证连接
                try {
                    console.log('发送测试命令验证连接...');
                    await serialPort.send(strToHexStr('P0F00L00'));
                    console.log('测试命令发送成功，连接验证通过');
                } catch (testErr) {
                    console.log('测试命令发送失败，连接可能有问题:', testErr);
                    // 如果测试命令失败，关闭串口并返回null
                    try {
                        serialPort.close();
                    } catch (closeErr) {
                        console.log('关闭测试串口时出错:', closeErr);
                    }
                    return null;
                }

                setUsbSerialport(serialPort);
                setIsConnected(true);
                console.log('USB设备连接成功，所有验证通过');
                return serialPort;
            } catch (err: any) {
                console.log('USB连接错误:', err);
                setIsConnected(false);
                setHasPermission(false);

                if (err.code === Codes.DEVICE_NOT_FOND) {
                    Alert.alert('设备未找到', '请检查频闪设备是否已连接');
                } else if (err.code === Codes.PERMISSION_DENIED) {
                    Alert.alert('权限被拒绝', '需要USB设备权限才能连接频闪设备');
                } else {
                    Alert.alert('连接失败', `错误: ${err.message || '未知错误'}`);
                }
                return null;
            }
        };

        // 断开USB连接
        const disconnectUSBDevice = async () => {
            usbSerialport?.close();
            setUsbSerialport(null);
            setIsConnected(false);

            // 使用统一的定时器清理函数
            clearAllTimers();
            setCountdown(10);
            setIsTesting(false);
            setCurrentTest(0);
            setTestResults([]);
            setTestSequence([]);
        };

        const detachUSBDevice = async () => {
            console.log('设备断开，清理连接状态');
            // 先关闭串口
            if (usbSerialport) {
                try {
                    usbSerialport.close();
                } catch (err) {
                    console.log('关闭串口时出错:', err);
                }
            }
            
            // 重置所有状态
            setUsbSerialport(null);
            setIsConnected(false);
            setHasPermission(false);
            setCleanConnection(true);
            
            // 使用统一的定时器清理函数
            clearAllTimers();
            setCountdown(10);
            setIsTesting(false);
            setCurrentTest(0);
            setTestResults([]);
            setTestSequence([]);
        }

        const attachUSBDevice = async () => {
            console.log('设备重新连接，开始重连流程');
            ToastAndroid.show('正在重新连接USB设备', ToastAndroid.SHORT);
            
            // 先彻底清理旧状态
            await detachUSBDevice();
            
            // 等待设备完全准备好
            await new Promise(resolve => setTimeout(resolve, 2000));
            
            // 尝试重新连接
            const serialPort = await connectUSBDevice();
            
            if (serialPort) {
                console.log('自动重连成功');
                setCleanConnection(false);
                // 确保连接状态正确设置
                setIsConnected(true);
                setHasPermission(true);
            } else {
                console.log('自动重连失败');
                // 如果重连失败，保持断开状态
                setCleanConnection(true);
                setIsConnected(false);
                setHasPermission(false);
            }
        }

        const strToHexStr = (str: string) => {
            const encoder = new TextEncoder();
            const bytes = encoder.encode(str);
            const hexStr = Array.from(bytes, (byte) =>
                byte.toString(16).padStart(2, "0")
            ).join("");
            return hexStr;
        }
        // 发送频闪控制命令
        const sendFlickerCommand = async (params: TestParams, lightOn: boolean = true) => {
            try {
                // 检查连接状态
                if (!usbSerialport || !isConnected) {
                    console.log('串口未连接，无法发送命令');
                    return;
                }

                // 构建命令: P1F30L01 格式
                // P1=灯亮, P0=灯灭, F30=频率30, L01=亮度01
                const command = `P${lightOn ? '1' : '0'}F${params.freq.toString().padStart(2, '0')}L${params.brightness.toString().padStart(2, '0')}`;
                //转hex
                await usbSerialport.send(strToHexStr(command));
                console.log('发送命令成功:', command);
            } catch (err: any) {
                console.log('发送命令错误:', err);
                // 如果发送失败，可能是连接问题，尝试重新连接
                if (err?.message && typeof err.message === 'string' && err.message.includes('connection')) {
                    console.log('检测到连接问题，尝试重新连接');
                    setIsConnected(false);
                    await connectUSBDevice();
                }
            }
        };

        // 检查连接是否真的有效
        const checkConnectionHealth = async () => {
            if (!usbSerialport || !isConnected) {
                return false;
            }

            try {
                // 发送一个简单的测试命令
                await usbSerialport.send(strToHexStr('P0F00L00'));
                return true;
            } catch (err) {
                console.log('连接健康检查失败:', err);
                // 连接可能已经断开，更新状态
                setIsConnected(false);
                setUsbSerialport(null);
                return false;
            }
        };

        // 配置要监听的USB相关广播动作
        BroadcastReceiver.setIntentActionConfig([
            {
                action: 'android.hardware.usb.action.USB_DEVICE_ATTACHED',
                datakey: 'device'
            },
            {
                action: 'android.hardware.usb.action.USB_DEVICE_DETACHED',
                datakey: 'device'
            },
            {
                action: 'android.hardware.usb.action.USB_ACCESSORY_ATTACHED',
                datakey: 'accessory'
            },
            {
                action: 'android.hardware.usb.action.USB_ACCESSORY_DETACHED',
                datakey: 'accessory'
            }
        ]);

        // 组件挂载时尝试连接设备并开始监听
        useEffect(() => {
            const sub = BroadcastReceiver.addEventListner(async (eventData) => {
                const {action} = eventData;
                console.log('收到USB广播:', action);

                if (action.includes("USB") && action.includes("DETACHED")) {
                    console.log('USB设备断开');
                    setCleanConnection(true);
                    // 立即清理连接状态
                    await detachUSBDevice();
                }
                if (action.includes("USB") && action.includes("ATTACHED")) {
                    console.log('USB设备重新连接');
                    // 延迟重连，确保设备完全准备好
                    setTimeout(async () => {
                        await attachUSBDevice();
                    }, 1000);
                }
            });
            
            // 初始连接
            connectUSBDevice();
            
            // 定期检查连接健康状态
            healthCheckIntervalRef.current = setInterval(async () => {
                if (isConnected) {
                    const isHealthy = await checkConnectionHealth();
                    if (!isHealthy) {
                        console.log('检测到连接异常，尝试重新连接');
                        await connectUSBDevice();
                    }
                }
            }, 10000); // 每10秒检查一次
            
            // 组件卸载时断开连接并停止监听
            return () => {
                sub.remove();
                clearAllTimers();
                disconnectUSBDevice();
            };
        }, []);

        // 组件卸载时清理所有定时器
        useEffect(() => {
            return () => {
                clearAllTimers();
            };
        }, []);

        // 运行单次测试
        const runSingleTest = async (params: TestParams) => {
            // 检查连接状态
            if (!isConnected || !usbSerialport) {
                console.log('串口未连接，无法运行测试');
                setIsTesting(false);
                return;
            }

            console.log(`开始测试: 频率${params.freq}Hz, 亮度${params.brightness}%`);

            // 使用统一的定时器清理函数
            clearAllTimers();
            
            // 重置倒计时为10秒，确保每次测试开始时都从10秒开始
            setCountdown(10);

            // 发送开启频闪命令
            await sendFlickerCommand(params, true);

            // 10秒倒计时
            timerRef.current = setInterval(() => {
                setCountdown(prevSeconds => {
                    const newSeconds = prevSeconds - 1;
                    if (newSeconds <= 0) {
                        clearInterval(timerRef.current);
                        timerRef.current = null;
                        setCountdown(10);

                        // 关闭频闪
                        sendFlickerCommand(params, false);

                        // 如果用户没有响应，自动进入下一测试
                        handleUserResponse(false);
                        return 10;
                    }
                    return newSeconds;
                });
            }, 1000);
        };

        // 开始测试
        const startTesting = () => {
            // 检查连接状态
            if (!isConnected || !usbSerialport) {
                Alert.alert('设备未连接', '请先连接频闪设备再开始测试');
                return;
            }

            // 生成随机测试序列
            const shuffledSequence = shuffleArray(baseTestSequence);
            setTestSequence(shuffledSequence);
            setTestResults([]);
            setIsTesting(true);
            setCurrentTest(0);
            runSingleTest(shuffledSequence[0]);
        };

        // 停止测试
        const stopTesting = async () => {
            // 关闭当前频闪
            if (testSequence[currentTest]) {
                await closeSequence();
            }

            setIsTesting(false);
            setCountdown(10);
            // 使用统一的定时器清理函数
            clearAllTimers();
        };

        const closeSequence = async () => {
            await sendFlickerCommand({freq: 0, brightness: 0}, false);
        }
        // 用户响应处理
        const handleUserResponse = async (sawFlicker: boolean) => {
            // 关闭当前频闪
            await closeSequence();

            // 确保 testSequence[currentTest] 存在
            if (!testSequence[currentTest]) {
                console.error('testSequence[currentTest] is undefined');
                return;
            }

            // 记录结果
            const newResult: TestResult = {
                params: testSequence[currentTest],
                sawFlicker,
                timestamp: Date.now()
            };
            const newResults = [...testResults, newResult];
            setTestResults(newResults);

            // 清除倒计时
            if (timerRef.current) {
                clearInterval(timerRef.current);
                timerRef.current = null;
            }

            // 重置倒计时状态为10秒，确保下次测试开始时显示正确的时间
            setCountdown(10);

            // 继续下一测试或结束
            if (currentTest < testSequence.length - 1) {
                // 进入间隔状态
                setIsInterval(true);
                setIntervalCountdown(3);

                // 间隔倒计时
                if (intervalTimerRef.current) {
                    clearInterval(intervalTimerRef.current);
                    intervalTimerRef.current = null;
                }
                intervalTimerRef.current = setInterval(() => {
                    setIntervalCountdown(prev => {
                        if (prev <= 1) {
                            if (intervalTimerRef.current) {
                                clearInterval(intervalTimerRef.current);
                                intervalTimerRef.current = null;
                            }
                            setIsInterval(false);

                            // 确保 testSequence[currentTest + 1] 存在
                            if (testSequence[currentTest + 1]) {
                                // 间隔结束后开始下一个测试
                                setCurrentTest(currentTest + 1);
                                runSingleTest(testSequence[currentTest + 1]);
                            } else {
                                console.error('testSequence[currentTest + 1] is undefined');
                            }
                            return 3;
                        }
                        return prev - 1;
                    });
                }, 1000);
            } else {
                // 测试完成
                setIsTesting(false);
                setCountdown(10);

                // 计算结果
                const flickerThreshold = calculateFlickerThreshold(newResults);

                // 如果需要重新测试，也保存测试结果
                if (flickerThreshold === -1) {
                    // 保存测试结果 - 0表示异常（测试不通过）
                    const testScore = 0;
                    console.log('保存频闪测试结果（测试不通过）:', {
                        measurement: {
                            value: testScore,
                            unit: ''
                        },
                        status: 'danger',
                        completedAt: new Date(),
                        details: {
                            testResults: newResults,
                            testCount: newResults.length,
                            hasErrors: true
                        }
                    });
                    addTestResult('Flicker', '频闪测试仪', {
                        value: testScore,
                        unit: '',
                        rawData: JSON.stringify(newResults),
                        timestamp: new Date().toISOString()
                    });
                    
                    Alert.alert(
                        '测试结果异常',
                        '检测到错误,测试结果已保存，是否重新进行测试？',
                        [
                            {
                                text: '否',
                                onPress: () => {
                                    setIsTesting(false);
                                    setCountdown(10);
                                }
                            },
                            {
                                text: '重新测试',
                                onPress: () => {
                                    setTestResults([]);
                                    startTesting();
                                }
                            }
                        ]
                    );
                    return;
                }

                const status = flickerThreshold > 20 ? 'normal' : flickerThreshold > 15 ? 'warning' : 'danger';

                // 保存测试结果 - 1表示正常，0表示异常
                const testScore = flickerThreshold === -1 ? 0 : 1;
                console.log('保存频闪测试结果:', {
                    measurement: {
                        value: testScore,
                        unit: ''
                    },
                    status: testScore === 1 ? 'normal' : 'danger',
                    completedAt: new Date(),
                    details: {
                        testResults: newResults,
                        testCount: newResults.length
                    }
                });
                addTestResult('Flicker', '频闪测试仪', {
                    value: testScore,
                    unit: '',
                    rawData: JSON.stringify(newResults),
                    timestamp: new Date().toISOString()
                });
                
                // 检查是否已完成所有测试
                if (isFlickerTestComplete(newResults)) {
                    // 显示检测完成提示对话框
                    handleTestComplete();
                }
            }
        };

        // 计算频闪阈值
        const calculateFlickerThreshold = (results: TestResult[]): number => {
            // 检查测试结果的正确性
            // 频率22及以下应该能看到闪烁，其他频率应该看不到闪烁
            const lowFreqResults = results.filter(r => r.params.freq <= 22);
            const highFreqResults = results.filter(r => r.params.freq > 22);

            // 检查是否有错误的回答
            const lowFreqErrors = lowFreqResults.filter(r => !r.sawFlicker); // 低频率但没看到闪烁
            const highFreqErrors = highFreqResults.filter(r => r.sawFlicker); // 高频率但看到了闪烁

            // 如果有任何错误回答，需要重新测试
            if (lowFreqErrors.length > 0 || highFreqErrors.length > 0) {
                return -1; // 返回-1表示需要重新测试
            }

            // 如果所有回答都正确，找到最高的能看到闪烁的频率
            const visibleFlickers = results
                .filter(r => r.sawFlicker && r.params.freq <= 22)
                .map(r => r.params.freq)
                .sort((a, b) => b - a);

            return visibleFlickers.length > 0 ? visibleFlickers[0] : 0;
        };

        const finishTest = () => {
            setShowCompletionDialog(false);
            navigation.goBack();
        };

        return (
            <SafeAreaView style={styles.container}>
                <View style={styles.header}>
                    <Text style={styles.title}>频闪测试仪</Text>
                    <Text style={styles.subtitle}>
                        测试您的频闪感知能力
                    </Text>
                </View>

                <ScrollView style={styles.content} contentContainerStyle={styles.contentContainer}>
                    {/* 连接状态指示器 */}
                    <View style={styles.modeIndicator}>
                        <View style={[
                            styles.statusIndicator,
                            {backgroundColor: isConnected ? '#4CAF50' : '#FF9800'}
                        ]}/>
                        <Text style={styles.modeText}>
                            {isConnected ? '设备已连接' : '设备未连接'}
                        </Text>
                        {!isConnected && (
                            <Text style={styles.permissionText}>
                                {hasPermission ? '有权限' : '需要权限'}
                            </Text>
                        )}
                    </View>

                    <View style={styles.connectionControls}>
                        <TouchableOpacity
                            style={[styles.connectionButton, isConnected ? styles.disconnectButton : styles.connectButton]}
                            onPress={isConnected ? disconnectUSBDevice : connectUSBDevice}
                        >
                            <Text style={styles.buttonText}>
                                {isConnected ? '断开设备' : '连接设备'}
                            </Text>
                        </TouchableOpacity>
                    </View>

                    {!isTesting ? (
                        <View style={styles.idleContainer}>
                            <Text style={styles.instruction}>
                                测试说明：{'\n'}
                                1. 测试将显示不同频率的闪烁光源{'\n'}
                                2. 如果您能看到闪烁，请点击&#34;是&#34;{'\n'}
                                3. 如果看不到闪烁，请点击&#34;否&#34;{'\n'}
                                4. 总共进行6次不同频率的测试{'\n'}
                                5. 系统将评估您的频闪感知能力
                            </Text>

                            <TouchableOpacity
                                style={styles.startButton}
                                onPress={startTesting}
                            >
                                <Text style={styles.startButtonText}>开始测试</Text>
                            </TouchableOpacity>
                        </View>
                    ) : (
                        isInterval ? (
                            <View style={styles.intervalContainer}>
                                <Text style={styles.intervalTitle}>
                                    测试间隔
                                </Text>

                                <View style={styles.simulationArea}>
                                    <Text style={styles.simulationText}>
                                        休息时间
                                    </Text>
                                    <View style={styles.lightSimulatorOff}/>
                                </View>

                                <Text style={styles.intervalCountdown}>
                                    下一测试将在 {intervalCountdown} 秒后开始
                                </Text>

                                <Text style={styles.intervalInfo}>
                                    已完成 {currentTest + 1}/{testSequence.length} 个测试
                                </Text>
                            </View>
                        ) : (
                            <View style={styles.testingContainer}>
                                <Text style={styles.testInfo}>
                                    测试 {currentTest + 1}/{testSequence.length}
                                </Text>

                                <View style={styles.simulationArea}>
                                    <Text style={styles.simulationText}>
                                        硬件频闪光源
                                    </Text>
                                    <View style={styles.lightSimulator}/>
                                </View>

                                <Text style={styles.countdown}>
                                    剩余时间: {countdown}秒
                                </Text>

                                <Text style={styles.params}>
                                    频率: {testSequence[currentTest]?.freq || 0}Hz |
                                    亮度: {testSequence[currentTest]?.brightness || 0}%
                                </Text>

                                <Text style={styles.question}>
                                    您能看到闪烁吗？
                                </Text>

                                <View style={styles.responseButtons}>
                                    <TouchableOpacity
                                        style={[styles.responseButton, styles.yesButton]}
                                        onPress={() => handleUserResponse(true)}
                                    >
                                        <Text style={styles.buttonText}>是 (看到闪烁)</Text>
                                    </TouchableOpacity>
                                    <TouchableOpacity
                                        style={[styles.responseButton, styles.noButton]}
                                        onPress={() => handleUserResponse(false)}
                                    >
                                        <Text style={styles.buttonText}>否 (未看到)</Text>
                                    </TouchableOpacity>
                                </View>

                                <TouchableOpacity
                                    style={styles.stopButton}
                                    onPress={stopTesting}
                                >
                                    <Text style={styles.buttonText}>停止测试</Text>
                                </TouchableOpacity>
                            </View>
                        )
                    )}

                    {/* 显示测试结果 */}
                    {testResults.length > 0 && !isTesting && (
                        <View style={styles.resultsContainer}>
                            <Text style={styles.resultsTitle}>测试完成！</Text>

                            <View style={styles.summaryContainer}>
                                <Text style={styles.statusText}>
                                    {calculateFlickerThreshold(testResults) === -1 ? '测试未通过，请重新测试' : '测试已完成'}
                                </Text>
                            </View>

                            <View style={styles.detailResults}>
                                <Text style={styles.detailTitle}>测试结果：</Text>
                                <View style={styles.resultItem}>
                                    <Text style={[styles.resultText, {fontSize: 18, fontWeight: 'bold', color: calculateFlickerThreshold(testResults) === -1 ? '#F44336' : '#4CAF50'}]}>
                                        {calculateFlickerThreshold(testResults) === -1 ? '不通过' : '通过'}
                                    </Text>
                                </View>
                            </View>

                            <View style={styles.finishButtons}>
                                <TouchableOpacity style={styles.retestButton} onPress={startTesting}>
                                    <Text style={styles.buttonText}>重新测试</Text>
                                </TouchableOpacity>
                                <TouchableOpacity style={styles.finishButton} onPress={finishTest}>
                                    <Text style={styles.buttonText}>完成</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    )}
                </ScrollView>
                
                {/* 检测完成提示对话框 */}
                {showCompletionDialog && (
                    <View style={styles.dialogOverlay}>
                        <View style={styles.dialogContainer}>
                            <Text style={styles.dialogTitle}>检测完成</Text>
                            <Text style={styles.dialogMessage}>您的检测已完成并已自动保存结果</Text>
                            <View style={styles.dialogButtons}>
                                <TouchableOpacity
                                    style={[styles.dialogButton, styles.stayButton]}
                                    onPress={() => setShowCompletionDialog(false)}
                                >
                                    <Text style={styles.stayButtonText}>继续检测</Text>
                                </TouchableOpacity>
                                <TouchableOpacity
                                    style={[styles.dialogButton, styles.returnButton]}
                                    onPress={finishTest}
                                >
                                    <Text style={styles.returnButtonText}>返回</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                )}
            </SafeAreaView>
        );
    }

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f6f8fa',
    },
    header: {
        backgroundColor: '#0a7ea4',
        paddingTop: 20,
        paddingBottom: 20,
        paddingHorizontal: 20,
        alignItems: 'center',
    },
    title: {
        fontSize: 24,
        fontWeight: 'bold',
        color: 'white',
        marginBottom: 8,
    },
    subtitle: {
        fontSize: 16,
        color: 'rgba(255,255,255,0.9)',
        textAlign: 'center',
    },
    content: {
        flex: 1,
    },
    contentContainer: {
        padding: 20,
    },
    modeIndicator: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: 'white',
        padding: 12,
        borderRadius: 8,
        marginBottom: 20,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 3,
    },
    statusIndicator: {
        width: 12,
        height: 12,
        borderRadius: 6,
        marginRight: 8,
    },
    modeText: {
        fontSize: 16,
        color: '#333',
    },
    connectionControls: {
        alignItems: 'center',
        marginBottom: 20,
    },
    connectionButton: {
        paddingHorizontal: 20,
        paddingVertical: 12,
        borderRadius: 8,
        minWidth: 120,
        alignItems: 'center',
    },
    connectButton: {
        backgroundColor: '#2196F3',
    },
    disconnectButton: {
        backgroundColor: '#F44336',
    },
    idleContainer: {
        alignItems: 'center',
    },
    instruction: {
        fontSize: 16,
        color: '#333',
        textAlign: 'center',
        lineHeight: 24,
        marginBottom: 30,
        backgroundColor: 'white',
        padding: 20,
        borderRadius: 12,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 3,
    },
    startButton: {
        backgroundColor: '#0a7ea4',
        paddingHorizontal: 40,
        paddingVertical: 15,
        borderRadius: 12,
    },
    startButtonText: {
        color: 'white',
        fontSize: 18,
        fontWeight: 'bold',
    },
    testingContainer: {
        alignItems: 'center',
        backgroundColor: 'white',
        padding: 20,
        borderRadius: 12,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 3,
    },
    testInfo: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#0a7ea4',
        marginBottom: 20,
    },
    simulationArea: {
        alignItems: 'center',
        marginBottom: 20,
    },
    simulationText: {
        fontSize: 16,
        color: '#666',
        marginBottom: 10,
    },
    lightSimulator: {
        width: 100,
        height: 100,
        borderRadius: 50,
        backgroundColor: '#FFD700',
        shadowColor: '#FFD700',
        shadowOffset: {width: 0, height: 0},
        shadowOpacity: 0.8,
        shadowRadius: 20,
        elevation: 10,
    },
    lightSimulatorOff: {
        width: 100,
        height: 100,
        borderRadius: 50,
        backgroundColor: '#555',
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 0},
        shadowOpacity: 0.3,
        shadowRadius: 5,
        elevation: 3,
    },
    countdown: {
        fontSize: 24,
        color: '#2196F3',
        fontWeight: 'bold',
        marginBottom: 15,
    },
    params: {
        fontSize: 16,
        color: '#666',
        marginBottom: 20,
        textAlign: 'center',
    },
    question: {
        fontSize: 18,
        color: '#333',
        fontWeight: 'bold',
        marginBottom: 20,
        textAlign: 'center',
    },
    responseButtons: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        width: '100%',
        marginBottom: 20,
    },
    responseButton: {
        paddingHorizontal: 20,
        paddingVertical: 12,
        borderRadius: 8,
        minWidth: 120,
        alignItems: 'center',
    },
    yesButton: {
        backgroundColor: '#4CAF50',
    },
    noButton: {
        backgroundColor: '#F44336',
    },
    stopButton: {
        backgroundColor: '#FF9800',
        paddingHorizontal: 30,
        paddingVertical: 12,
        borderRadius: 8,
        alignItems: 'center',
    },
    buttonText: {
        color: 'white',
        fontWeight: 'bold',
        textAlign: 'center',
    },
    resultsContainer: {
        backgroundColor: 'white',
        padding: 20,
        borderRadius: 12,
        marginTop: 20,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 3,
    },
    resultsTitle: {
        fontSize: 24,
        fontWeight: 'bold',
        color: '#0a7ea4',
        textAlign: 'center',
        marginBottom: 20,
    },
    summaryContainer: {
        alignItems: 'center',
        marginBottom: 20,
    },
    summaryText: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 8,
    },
    statusText: {
        fontSize: 16,
        color: '#666',
    },
    detailResults: {
        marginBottom: 20,
    },
    detailTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 10,
    },
    resultItem: {
        paddingVertical: 4,
    },
    resultText: {
        fontSize: 14,
        color: '#666',
    },
    finishButtons: {
        flexDirection: 'row',
        justifyContent: 'space-around',
    },
    retestButton: {
        backgroundColor: '#FF9800',
        paddingHorizontal: 20,
        paddingVertical: 12,
        borderRadius: 8,
        minWidth: 100,
        alignItems: 'center',
    },
    finishButton: {
        backgroundColor: '#4CAF50',
        paddingHorizontal: 20,
        paddingVertical: 12,
        borderRadius: 8,
        minWidth: 100,
        alignItems: 'center',
    },
    intervalContainer: {
        alignItems: 'center',
        backgroundColor: '#f0f0f0',
        padding: 20,
        borderRadius: 12,
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 3,
    },
    intervalTitle: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#555',
        marginBottom: 20,
    },
    intervalCountdown: {
        fontSize: 18,
        color: '#0a7ea4',
        fontWeight: 'bold',
        marginTop: 15,
        marginBottom: 10,
    },
    intervalInfo: {
        fontSize: 16,
        color: '#666',
        marginTop: 10,
    },
    permissionText: {
        fontSize: 12,
        color: '#666',
        marginLeft: 8,
        fontStyle: 'italic',
    },
    // 检测完成提示对话框样式
    dialogOverlay: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'center',
        alignItems: 'center',
        zIndex: 1000,
    },
    dialogContainer: {
        backgroundColor: 'white',
        borderRadius: 12,
        padding: 24,
        width: '80%',
        maxWidth: 320,
        alignItems: 'center',
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.25,
        shadowRadius: 4,
        elevation: 5,
    },
    dialogTitle: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 16,
    },
    dialogMessage: {
        fontSize: 16,
        color: '#666',
        textAlign: 'center',
        marginBottom: 24,
    },
    dialogButtons: {
        flexDirection: 'row',
        width: '100%',
        justifyContent: 'space-between',
    },
    dialogButton: {
        flex: 1,
        paddingVertical: 12,
        paddingHorizontal: 16,
        borderRadius: 8,
        alignItems: 'center',
        marginHorizontal: 8,
    },
    stayButton: {
        backgroundColor: '#f0f0f0',
    },
    returnButton: {
        backgroundColor: '#0a7ea4',
    },
    stayButtonText: {
        fontSize: 16,
        color: '#333',
        fontWeight: 'bold',
    },
    returnButtonText: {
        fontSize: 16,
        color: 'white',
        fontWeight: 'bold',
    }
});

export default FlickerDevice;